export default {
    data() {
        return {
            todayPower: '0.00',
            monthPower: '0.00',
            dailyChartData: {
                categories: [],
                series: [{
                    name: '用电量',
                    data: [],
                }],
            },
            monthlyChartData: {
                categories: [],
                series: [{
                    name: '用电量',
                    data: [],
                }],
            },
            statusBarHeight: 0,
            dailyDataTooltip: {
                show: false,
                x: 0,
                y: 0,
                time: '',
                value: ''
            },
            monthlyDataTooltip: {
                show: false,
                x: 0,
                y: 0,
                time: '',
                value: ''
            },
            dailyChartInfo: {
                padding: 40,
                width: 0,
                height: 0,
                chartWidth: 0,
                chartHeight: 0,
                maxValue: 0,
                minValue: 0,
                pointsCoordinate: []
            },
            monthlyChartInfo: {
                padding: 40,
                width: 0,
                height: 0,
                chartWidth: 0,
                chartHeight: 0,
                maxValue: 0,
                minValue: 0,
                pointsCoordinate: []
            },
            devicePieData: [
                { name: '温湿度设备', value: 15, color: '#3B82F6' },     // 柔和的蓝色
                { name: '光照强度', value: 12, color: '#10B981' },       // 优雅的绿色
                { name: '烟雾检测', value: 8, color: '#EF4444' },        // 柔和的红色
                { name: '空气质量', value: 10, color: '#8B5CF6' },       // 柔和的紫色
                { name: '人体传感', value: 5, color: '#F97316' },        // 温和的橙色
                { name: '蜂鸣器', value: 3, color: '#14B8A6' },          // 青绿色
                { name: '灯光控制', value: 7, color: '#FBBF24' }         // 温和的黄色
            ],
            // 饼图动画相关信息
            pieChartInfo: {
                padding: 40,
                width: 0,
                height: 0,
                chartWidth: 0,
                chartHeight: 0
            },
            // 添加动画触发标志位
            dailyChartAnimated: false,
            monthlyChartAnimated: false,
            devicePieChartAnimated: false,
            // 新增状态控制
            showPieChart: true,
            // 用电量情况对比
            powerComparisonData: [
                {
                    label: '总用电量',
                    currentMonth: 1207.77,
                    previousMonth: 1270.55,
                    unit: 'kW·h'
                },
                {
                    label: '峰值用电设备',
                    currentMonth: 25.0,
                    previousMonth: 22.5,
                    unit: '%'
                },
                {
                    label: '用电高峰时段',
                    currentMonth: 18,
                    previousMonth: 20,
                    unit: '小时'
                },
                {
                    label: '用电成本',
                    currentMonth: 360.00,
                    previousMonth: 380.50,
                    unit: '元'
                }
            ],
            powerComparisonChartAnimated: false
        };
    },
    onPageScroll(e) {
        // 获取设备信息
        const systemInfo = wx.getSystemSetting();
        const screenHeight = systemInfo.screenHeight;

        // 查询图表的位置
        const query = wx.createSelectorQuery();
        query.select('#devicePieChart').boundingClientRect();
        query.select('#dailyPowerChart').boundingClientRect();
        query.select('#monthlyPowerChart').boundingClientRect();
        query.select('#powerComparisonChart').boundingClientRect();
        query.exec((res) => {
            // 单独处理每个图表的动画触发
            this.checkAndTriggerAnimation(res[0], 'devicePie', () => {
                this.drawPieChartWithAnimation();
            });

            this.checkAndTriggerAnimation(res[1], 'dailyChart', () => {
                this.drawChartWithAnimation('daily');
            });

            this.checkAndTriggerAnimation(res[2], 'monthlyChart', () => {
                this.drawChartWithAnimation('monthly');
            });

            this.checkAndTriggerAnimation(res[0], 'powerComparison', () => {
                this.drawPowerComparisonChart();
            });
        });
    },
    onLoad() {
        const systemInfo = wx.getSystemSetting();
        this.statusBarHeight = systemInfo.statusBarHeight;
    },
    onReady() {
        this.generateMockData();
        this.drawChartWithAnimation('daily');
        this.drawChartWithAnimation('monthly');
    },
    methods: {
        // 新增通用的动画触发检查方法
        checkAndTriggerAnimation(rect, type, animationCallback) {
            const systemInfo = wx.getSystemInfoSync();
            const screenHeight = systemInfo.screenHeight;

            // 根据不同类型使用不同的动画标志
            const animationFlagMap = {
                'devicePie': 'devicePieChartAnimated',
                'dailyChart': 'dailyChartAnimated',
                'monthlyChart': 'monthlyChartAnimated'
            };

            const flagKey = animationFlagMap[type];

            // 检查是否已经动画过
            if (this[flagKey]) return;

            // 严格的可视区域判断
            if (rect &&
                rect.top < screenHeight * 0.8 &&
                rect.bottom > screenHeight * 0.2) {
                // 标记为已动画
                this[flagKey] = true;

                // 执行动画回调
                animationCallback();
            }
        },
        generateMockData() {
            // 24小时用电量数据
            const hours = Array.from({ length: 24 }, (_, i) => `${i.toString().padStart(2, '0')}:00`);
            const dailyData = hours.map((_, index) => {
                if (index >= 7 && index <= 10) return +(Math.random() * 3 + 2).toFixed(2);
                if (index >= 17 && index <= 21) return +(Math.random() * 3 + 2).toFixed(2);
                return +(Math.random() * 1.5).toFixed(2);
            });

            this.dailyChartData.categories = hours;
            this.dailyChartData.series[0].data = dailyData;
            this.todayPower = dailyData.reduce((sum, val) => sum + val, 0).toFixed(2);

            // 月用电量数据（30天）
            const days = Array.from({ length: 30 }, (_, i) => `${i + 1}日`);
            const monthlyData = days.map(() => +(Math.random() * 5 + 1).toFixed(2));

            this.monthlyChartData.categories = days;
            this.monthlyChartData.series[0].data = monthlyData;
            this.monthPower = (this.todayPower * 30 + Math.random() * 50).toFixed(2);
        },
        onChartTouch(type, event) {
            const canvasId = type === 'daily' ? '#dailyPowerChart' : '#monthlyPowerChart';
            const query = wx.createSelectorQuery();
            query.select(canvasId).boundingClientRect();
            query.exec((res) => {
                const rect = res[0];
                const touches = event.touches[0];

                // 计算相对于画布的触摸坐标
                const touchX = touches.clientX - rect.left;
                const touchY = touches.clientY - rect.top;

                const chartInfo = type === 'daily' ? this.dailyChartInfo : this.monthlyChartInfo;
                const nearestPoint = this.findNearestPoint(touchX, touchY, chartInfo);

                const dataTooltip = type === 'daily' ? this.dailyDataTooltip : this.monthlyDataTooltip;
                const chartData = type === 'daily' ? this.dailyChartData : this.monthlyChartData;

                if (nearestPoint) {
                    dataTooltip.show = true;
                    dataTooltip.x = nearestPoint.x;

                    // 根据点的位置动态调整tooltip位置
                    dataTooltip.y = nearestPoint.isUpperHalf
                        ? nearestPoint.y + 20
                        : nearestPoint.y - 60;

                    dataTooltip.time = chartData.categories[nearestPoint.index];
                    dataTooltip.value = chartData.series[0].data[nearestPoint.index].toFixed(2);
                }
            });
        },
        onChartTouchEnd() {
            this.dailyDataTooltip.show = false;
            this.monthlyDataTooltip.show = false;
        },
        findNearestPoint(touchX, touchY, chartInfo) {
            if (!chartInfo.pointsCoordinate.length) return null;

            for (let i = 0; i < chartInfo.pointsCoordinate.length; i++) {
                const point = chartInfo.pointsCoordinate[i];
                const distance = Math.sqrt(
                    Math.pow(point.x - touchX, 2) + Math.pow(point.y - touchY, 2)
                );

                if (distance < 20) {  // 20像素范围内视为点击到点
                    return {
                        x: point.x,
                        y: point.y,
                        index: i,
                        isUpperHalf: point.y < (chartInfo.height / 2)  // 使用传入的 chartInfo
                    };
                }
            }
            return null;
        },
        // 修改动画方法，确保只绘制一次
        drawChartWithAnimation(type) {
            // 检查是否已经绘制过
            if (type === 'daily' && this.dailyChartAnimated) return;
            if (type === 'monthly' && this.monthlyChartAnimated) return;

            const canvasId = type === 'daily' ? '#dailyPowerChart' : '#monthlyPowerChart';
            const query = wx.createSelectorQuery();
            query.select(canvasId)
                .fields({ node: true, size: true })
                .exec((res) => this.renderChartAnimation(res, type));
        },
        renderChartAnimation(res, type) {
            console.log('饼图开始绘制')
            const canvas = res[0].node;
            const ctx = canvas.getContext('2d');

            // 获取设备像素比并设置画布大小
            const dpr = wx.getSystemInfoSync().pixelRatio;
            canvas.width = res[0].width * dpr;
            canvas.height = res[0].height * dpr;
            ctx.scale(dpr, dpr);

            const chartData = type === 'daily' ? this.dailyChartData : this.monthlyChartData;
            const data = chartData.series[0].data;
            const categories = chartData.categories;
            const width = res[0].width;
            const height = res[0].height;

            const padding = 40;
            const chartWidth = width - 2 * padding;
            const chartHeight = height - 2 * padding;

            // 保存图表信息
            const chartInfo = {
                padding,
                width,
                height,
                chartWidth,
                chartHeight,
                maxValue: Math.max(...data),
                minValue: Math.min(...data),
                pointsCoordinate: []
            };

            if (type === 'daily') {
                this.dailyChartInfo = chartInfo;
            } else {
                this.monthlyChartInfo = chartInfo;
            }

            const maxValue = chartInfo.maxValue;
            const minValue = chartInfo.minValue;

            // 创建渐变背景
            const gradient = ctx.createLinearGradient(0, 0, 0, height);
            gradient.addColorStop(0, 'rgba(57, 117, 212, 0.1)');
            gradient.addColorStop(1, 'rgba(57, 117, 212, 0.02)');

            // 动画函数
            const animate = (progress) => {
                // 清空画布并设置背景
                ctx.clearRect(0, 0, width, height);
                ctx.fillStyle = '#f9fbff';
                ctx.fillRect(0, 0, width, height);

                // 绘制网格线
                ctx.strokeStyle = '#e6f1ff';
                ctx.lineWidth = 1;
                const gridLines = 5;
                for (let i = 0; i <= gridLines; i++) {
                    const y = padding + (chartHeight * i) / gridLines;
                    ctx.beginPath();
                    ctx.moveTo(padding, y);
                    ctx.lineTo(width - padding, y);
                    ctx.stroke();
                }

                // 绘制坐标轴
                ctx.strokeStyle = '#d1e6ff';
                ctx.lineWidth = 2;

                // X轴
                ctx.beginPath();
                ctx.moveTo(padding, height - padding);
                ctx.lineTo(width - padding, height - padding);
                ctx.stroke();

                // Y轴
                ctx.beginPath();
                ctx.moveTo(padding, padding);
                ctx.lineTo(padding, height - padding);
                ctx.stroke();

                // 绘制折线
                ctx.beginPath();
                ctx.strokeStyle = '#3975d4';
                ctx.lineWidth = 3;

                // 创建阴影效果
                ctx.shadowColor = 'rgba(57, 117, 212, 0.3)';
                ctx.shadowBlur = 10;

                const animatedData = data.slice(0, Math.ceil(data.length * progress));
                const pointsCoordinate = [];

                animatedData.forEach((value, index) => {
                    const x = padding + (chartWidth * index) / (data.length - 1);
                    const y = height - padding -
                        ((value - minValue) / (maxValue - minValue)) * chartHeight;

                    pointsCoordinate.push({ x, y });

                    if (index === 0) {
                        ctx.moveTo(x, y);
                    } else {
                        ctx.lineTo(x, y);
                    }
                });

                ctx.stroke();

                // 关闭阴影
                ctx.shadowBlur = 0;

                // 填充渐变背景
                if (progress === 1) {
                    ctx.beginPath();
                    pointsCoordinate.forEach((point, index) => {
                        if (index === 0) {
                            ctx.moveTo(point.x, point.y);
                        } else {
                            ctx.lineTo(point.x, point.y);
                        }
                    });

                    ctx.lineTo(width - padding, height - padding);
                    ctx.lineTo(padding, height - padding);
                    ctx.closePath();

                    ctx.fillStyle = gradient;
                    ctx.fill();

                    // 更新点坐标数组
                    if (type === 'daily') {
                        this.dailyChartInfo.pointsCoordinate = pointsCoordinate;
                    } else {
                        this.monthlyChartInfo.pointsCoordinate = pointsCoordinate;
                    }

                    // 绘制数据点
                    ctx.fillStyle = '#3975d4';
                    pointsCoordinate.forEach((point) => {
                        ctx.beginPath();
                        ctx.arc(point.x, point.y, 4, 0, 2 * Math.PI);
                        ctx.fill();
                    });

                    // 绘制X轴标签
                    ctx.fillStyle = '#8b9cb3';
                    ctx.font = '10px Arial';
                    ctx.textAlign = 'center';
                    data.forEach((_, index) => {
                        if (index % Math.ceil(data.length / 6) === 0) {
                            const x = padding + (chartWidth * index) / (data.length - 1);
                            ctx.fillText(categories[index], x, height - 10);
                        }
                    });

                    // 绘制Y轴标签
                    ctx.textAlign = 'right';
                    [minValue, (minValue + maxValue) / 2, maxValue].forEach((value) => {
                        const y = height - padding -
                            ((value - minValue) / (maxValue - minValue)) * chartHeight;
                        ctx.fillText(value.toFixed(1), padding - 10, y + 4);
                    });
                }
            };

            // 动画控制
            const duration = 1800; // 稍微延长动画时间
            const startTime = Date.now();

            const step = () => {
                const currentTime = Date.now();
                const elapsed = currentTime - startTime;
                const progress = Math.min(elapsed / duration, 1);

                // 使用缓动函数使动画更自然
                const easedProgress = 1 - Math.pow(1 - progress, 4);

                animate(easedProgress);

                if (progress < 1) {
                    canvas.requestAnimationFrame(step);
                }
            };

            canvas.requestAnimationFrame(step);
        },
        //绘制饼图
        drawPieChartWithAnimation() {
            const query = wx.createSelectorQuery();
            query.select('#devicePieChart')
                .fields({ node: true, size: true })
                .exec((res) => this.renderPieChartAnimation(res));
        },
        renderPieChartAnimation(res) {
            const canvas = res[0].node;
            const ctx = canvas.getContext('2d');

            // 获取设备像素比并设置画布大小
            const dpr = wx.getSystemInfoSync().pixelRatio;
            canvas.width = res[0].width * dpr;
            canvas.height = res[0].height * dpr;
            ctx.scale(dpr, dpr);

            const width = res[0].width;
            const height = res[0].height;
            const padding = 40;
            const chartWidth = width - 2 * padding;
            const chartHeight = height - 2 * padding;

            // 保存图表信息
            this.pieChartInfo = {
                padding,
                width,
                height,
                chartWidth,
                chartHeight
            };

            const centerX = width / 2;
            const centerY = height / 2;
            const radius = Math.min(chartWidth, chartHeight) / 2;

            const total = this.devicePieData.reduce((sum, item) => sum + item.value, 0);

            // 动画函数
            const animate = (progress) => {
                // 清空画布
                ctx.clearRect(0, 0, width, height);
                ctx.fillStyle = '#f9fbff';
                ctx.fillRect(0, 0, width, height);

                let startAngle = -Math.PI / 2;

                this.devicePieData.forEach((item) => {
                    const percentage = item.value / total;
                    const angle = percentage * 2 * Math.PI * progress;

                    ctx.beginPath();
                    ctx.moveTo(centerX, centerY);
                    ctx.fillStyle = item.color;
                    // 添加阴影效果
                    ctx.shadowColor = 'rgba(0,0,0,0.1)';
                    ctx.shadowBlur = 10;

                    ctx.arc(centerX, centerY, radius, startAngle, startAngle + angle);
                    ctx.closePath();
                    ctx.fill();

                    // 清除阴影
                    ctx.shadowBlur = 0;

                    // 如果动画完成，添加百分比文字
                    if (progress === 1) {
                        const labelAngle = startAngle + angle / 2;
                        const labelX = centerX + Math.cos(labelAngle) * (radius * 0.7);
                        const labelY = centerY + Math.sin(labelAngle) * (radius * 0.7);

                        ctx.fillStyle = 'white';
                        ctx.font = '12px Arial';
                        ctx.textAlign = 'center';
                        ctx.textBaseline = 'middle';
                        ctx.fillText(`${(percentage * 100).toFixed(1)}%`, labelX, labelY);
                    }

                    startAngle += angle;
                });


            };

            // 动画控制
            const duration = 1500; // 动画持续时间
            const startTime = Date.now();

            const step = () => {
                const currentTime = Date.now();
                const elapsed = currentTime - startTime;
                const progress = Math.min(elapsed / duration, 1);

                // 使用缓动函数使动画更自然
                const easedProgress = 1 - Math.pow(1 - progress, 4);

                animate(easedProgress);

                if (progress < 1) {
                    canvas.requestAnimationFrame(step);
                }
            };

            canvas.requestAnimationFrame(step);
        },

        // 切换图表类型
        toggleChartType() {
            this.showPieChart = !this.showPieChart;
            this.$nextTick(() => {
                if (this.showPieChart) {
                    this.drawPieChartWithAnimation();
                } else {
                    this.drawBarChartWithAnimation();
                }
            });
        },

        // 在methods中添加柱形图绘制方法
        drawBarChartWithAnimation() {
            const query = wx.createSelectorQuery();
            query.select('#deviceBarChart')
                .fields({ node: true, size: true })
                .exec((res) => this.renderBarChartAnimation(res));
        },

        renderBarChartAnimation(res) {
            const canvas = res[0].node;
            const ctx = canvas.getContext('2d');
            const dpr = wx.getSystemInfoSync().pixelRatio;

            // 画布尺寸设置（关键修复点）
            canvas.width = res[0].width * dpr;
            canvas.height = res[0].height * dpr;
            ctx.scale(dpr, dpr);

            const width = res[0].width;
            const height = res[0].height;
            const padding = 40;
            const chartWidth = width - 2 * padding;
            const chartHeight = height - 2 * padding;

            // 计算最大值和总量
            const maxValue = Math.max(...this.devicePieData.map(item => item.value));
            const total = this.devicePieData.reduce((sum, item) => sum + item.value, 0);

            // 动画函数（保持与饼图一致的动画逻辑）
            const animate = (progress) => {
                ctx.clearRect(0, 0, width, height);
                ctx.fillStyle = '#f9fbff';
                ctx.fillRect(0, 0, width, height);

                // 绘制坐标轴
                ctx.strokeStyle = '#d1e6ff';
                ctx.lineWidth = 2;

                // Y轴
                ctx.beginPath();
                ctx.moveTo(padding, padding);
                ctx.lineTo(padding, height - padding);
                ctx.stroke();

                // X轴
                ctx.beginPath();
                ctx.moveTo(padding, height - padding);
                ctx.lineTo(width - padding, height - padding);
                ctx.stroke();

                // 绘制柱子
                const barCount = this.devicePieData.length;
                const barWidth = (chartWidth / barCount) * 0.6;
                const spacing = (chartWidth / barCount) * 0.2;

                this.devicePieData.forEach((item, index) => {
                    const x = padding + spacing + (chartWidth / barCount) * index;
                    const rawHeight = (item.value / maxValue) * chartHeight;
                    const animatedHeight = rawHeight * progress;

                    // 使用饼图对应颜色
                    ctx.fillStyle = item.color;

                    // 绘制柱子主体
                    ctx.fillRect(
                        x,
                        height - padding - animatedHeight,
                        barWidth,
                        animatedHeight
                    );

                    // 绘制百分比文字（动画完成后显示）
                    if (progress === 1) {
                        ctx.fillStyle = '#666';
                        ctx.font = `${4 * dpr}px Arial`;
                        ctx.textAlign = 'center';
                        ctx.fillText(
                            `${((item.value / total) * 100).toFixed(1)}%`,
                            x + barWidth / 2,
                            height - padding - animatedHeight - 3 * dpr
                        );
                    }
                });


            };

            // 动画控制（与饼图保持一致）
            const duration = 1500;
            const startTime = Date.now();

            const step = () => {
                const currentTime = Date.now();
                const elapsed = currentTime - startTime;
                const progress = Math.min(elapsed / duration, 1);
                const easedProgress = 1 - Math.pow(1 - progress, 4);

                animate(easedProgress);

                if (progress < 1) {
                    canvas.requestAnimationFrame(step);
                } else {
                    // 添加触摸交互（参考折线图逻辑）
                    this.initBarChartTouch(canvas, width, height, padding);
                }
            };

            canvas.requestAnimationFrame(step);
        },
        // 初始化柱形图触摸交互
        initBarChartTouch(canvas, width, height, padding) {
            // 实现类似折线图的触摸交互逻辑...
        },
        // 用电量对比图绘制
        drawPowerComparisonChart() {
            const query = wx.createSelectorQuery();
            query.select('#powerComparisonChart')
                .fields({ node: true, size: true })
                .exec((res) => this.renderPowerComparisonChart(res));
        },
        renderPowerComparisonChart(res) {
            const canvas = res[0].node;
            const ctx = canvas.getContext('2d');
            const dpr = wx.getSystemInfoSync().pixelRatio;

            canvas.width = res[0].width * dpr;
            canvas.height = res[0].height * dpr;
            ctx.scale(dpr, dpr);

            const width = res[0].width;
            const height = res[0].height;

            // 简洁的颜色配置
            const colors = [
                ['#00fff3', '#ff0000'],   // 总用电量
                ['#00fff3', '#ff0000'],   // 峰值用电设备
                ['#00fff3', '#ff0000'],  // 用电高峰时段
                ['#00fff3', '#ff0000'],   // 用电成本
            ];

            const animate = (progress) => {
                ctx.clearRect(0, 0, width, height);
                ctx.fillStyle = '#f9fbff';
                ctx.fillRect(0, 0, width, height);

                const barHeight = 25;  // 柱子高度
                const gap = 20;         // 柱子间距
                const maxBarWidth = width * 0.85;  // 减小柱子宽度
                const verticalOffset = 50;  // 向下垂直偏移

                this.powerComparisonData.forEach((item, index) => {
                    const y = (barHeight + gap) * index + verticalOffset;
                    const prevBarWidth = (item.previousMonth / this.getMaxValue(item)) * maxBarWidth * progress;
                    const currBarWidth = (item.currentMonth / this.getMaxValue(item)) * maxBarWidth * progress;

                    // 标签
                    ctx.fillStyle = '#666';
                    ctx.font = '12px Arial';
                    ctx.textAlign = 'center';
                    ctx.fillText(item.label, width / 2, y - 8);

                    // 左侧柱子
                    const gradient1 = ctx.createLinearGradient(0, y, prevBarWidth, y + barHeight);
                    gradient1.addColorStop(0, colors[index][0]);
                    // gradient1.addColorStop(1, colors[index][1]);
                    ctx.fillStyle = gradient1;
                    const prevBarX = width / 2 - prevBarWidth;
                    ctx.fillRect(prevBarX, y, prevBarWidth, barHeight);

                    // 右侧柱子
                    const gradient2 = ctx.createLinearGradient(width / 2, y, width / 2 + currBarWidth, y + barHeight);
                    gradient2.addColorStop(0, colors[index][1]);
                    // gradient2.addColorStop(1, colors[index][0]);
                    ctx.fillStyle = gradient2;
                    ctx.fillRect(width / 2, y, currBarWidth, barHeight);

                    // 左侧数值
                    ctx.fillStyle = '#666';
                    ctx.font = '12px "Segoe UI", "PingFang SC", sans-serif';
                    ctx.textAlign = 'left';
                    ctx.fillText(`${item.previousMonth}${item.unit}`, 5, y + barHeight / 2 + 5);

                    // 右侧数值
                    ctx.textAlign = 'right';
                    ctx.fillText(`${item.currentMonth}${item.unit}`, width - 5, y + barHeight / 2 + 5);
                });
            };

            const duration = 7500;
            const startTime = Date.now();

            const step = () => {
                const currentTime = Date.now();
                const elapsed = currentTime - startTime;
                const progress = Math.min(elapsed / duration, 1);
                const easedProgress = 1 - Math.pow(1 - progress, 4);

                animate(easedProgress);

                if (progress < 1) {
                    canvas.requestAnimationFrame(step);
                }
            };

            canvas.requestAnimationFrame(step);
        },
        getMaxValue(item) {
            const maxValues = {
                '总用电量': 1300,
                '峰值用电设备': 30,
                '用电高峰时段': 24,
                '用电成本': 400
            };
            return maxValues[item.label];
        }


    }
};